package com.feige.filter;

import com.feige.constant.Constants;
import com.feige.pojo.SecurityUser;
import com.feige.utils.http.ResponseUtil;
import com.feige.utils.jwt.JwtInfo;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author feige
 */
public class JwtFilter extends OncePerRequestFilter {

    private final RedisUtils redisUtils;

    private final JwtUtils jwtUtils;

    public JwtFilter(RedisUtils redisUtils, JwtUtils jwtUtils) {
        this.redisUtils = redisUtils;
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (!jwtUtils.isTokenExpire(request)) {
            JwtInfo jwtInfo = jwtUtils.getJwtInfoByToken(request);
            if (jwtInfo != null){
                String key = Constants.LOGIN_USER_KEY + jwtInfo.getId();
                SecurityUser user = (SecurityUser) redisUtils.get(key);
                if (user != null){
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    chain.doFilter(request, response);
                }else {
                    ResponseUtil.outError(response);
                }
            }else {
                ResponseUtil.outError(response);
            }
        }else {
            ResponseUtil.outError(response);
        }
    }
}
